package com.kaibes.module.jwt.util;

import java.security.PrivateKey;
import java.security.PublicKey;
import java.util.Date;
import java.util.List;

import org.springframework.core.io.ClassPathResource;
import org.springframework.security.rsa.crypto.KeyStoreKeyFactory;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.JwsHeader;
import io.jsonwebtoken.Jwt;
import io.jsonwebtoken.Jwts;

public class JwtUtils {

	private static PrivateKey privateKey = null;
    private static PublicKey publicKey = null;
    
    static { // 将证书文件里边的私钥公钥拿出来
        try {
            KeyStoreKeyFactory keyStoreKeyFactory = new KeyStoreKeyFactory(new ClassPathResource("nacos-jwt.jks"), "123456".toCharArray());
            privateKey = keyStoreKeyFactory.getKeyPair("nacos-jwt").getPrivate();
            publicKey = keyStoreKeyFactory.getKeyPair("nacos-jwt").getPublic();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    
	public static String createToken(Integer userId, String username, List<String> authorities) {
		return Jwts.builder()
				.setAudience("user-token")
				.setExpiration(new Date(System.currentTimeMillis() + 3600000))
				.claim("user_id", userId)
				.claim("user_name", username)
				.claim("authorities", authorities)
				.signWith(privateKey).compact();
	}
	
	@SuppressWarnings({"rawtypes", "unchecked"})
	public static Jwt<JwsHeader, Claims> parseToken(String token) {
		return Jwts.parserBuilder().setSigningKey(publicKey).build().parse(token);
	}
	
}
